package models

import (
	"errors"
	"github.com/astaxie/beego/orm"
)

type ServerInfo struct {
	Id int
	Sname string `orm:"null"`
	Sip string `orm:"null"`
	SwebPort string `orm:"null"`
	SmqttPort string `orm:"null"`
	Stype string `orm:"null"`
	Sremark string `orm:"null"`
}

type ResponseStruct struct {
	SuccessCode int
	MessageCode int
	Message ServerInfo
}
type ResponseErrStruct struct {
	SuccessCode int
	MessageCode int
	Message string
}
func init()  {
	orm.RegisterModel(new(ServerInfo))
}

func ServerAdd(serverinfo ServerInfo)(int64,error)  {
	if serverinfo.Sname==""{
		return 0,errors.New("the name is empty")
	}else {
		_,er:=SearchByName(serverinfo.Sname)
		if er==nil{
			return 0,errors.New("the server already exists")
		}else {
			o:=orm.NewOrm()
			return o.Insert(&serverinfo)
		}
	}

}

func ServerAll()([]ServerInfo, error)  {
	o:=orm.NewOrm()
	var s []ServerInfo
	//num,err:=o.Raw("select * from server_info").QueryRows(&s)
	//fmt.Println(num,err)
	serverinfo:=new(ServerInfo)
	qs:=o.QueryTable(serverinfo)
	_,err:=qs.OrderBy("id").All(&s)
	return s,err
}

func ServerDel(name string)(int64,error)  {
	ser,er:=SearchByName(name)
	if er==nil{
		o:=orm.NewOrm()
		return o.Delete(&ServerInfo{Id:ser.Id})
	}else {
		return 0,errors.New("the server don't exists")
	}
}

func ServerSearchByName(name string)([]ServerInfo,error)  {
	o:=orm.NewOrm()
	var s []ServerInfo
	serverinfo:=new(ServerInfo)
	qs:=o.QueryTable(serverinfo)
	_,err:=qs.Filter("sname__icontains",name).OrderBy("sname").All(&s)
	return  s,err
}

func SearchByName(name string)(ServerInfo,error)  {
	o:=orm.NewOrm()
	serverinfo:=ServerInfo{Sname:name}
	err:=o.Read(&serverinfo,"sname")
	return  serverinfo,err
}